// pages/edu/timetable/index.js
/**
 * @Author:Kindear
 * @Date:2021-09-05
 * @Extend:练手课表 & ColorUI
 */

 /**
  * @Author:Kindear
  * @Date:2021-09-16
  * @Extend:校园小程序&ColorUI
  */
/**记录用户选择的当前课表 */
function serializePathQuery(params) {
    const str = [];
    for (let key in params)
        if (params.hasOwnProperty(key)) {
            str.push(key + "=" + params[key]);
        }
    return str.join("&");
}
import config from "../../config";
import dayjs from "dayjs";
const app = getApp();
Page({
    data: {
        login: false,
        StatusBar: app.globalData.StatusBar,
        CustomBar: app.globalData.CustomBar,
        displayArea: app.globalData.displayArea,
        // ImgUrl: app.globalData.ImgUrl,
        colorList: config.colorList,
        weeksSwitch: false,
        semester: null,
        nowM: 1, // 当前月份
        haveCouple: null, // 情侣ID,用于判断是否绑定情侣
        showWeek: 1, // 显示周
        currentWeek: 1, // 当前周
        weeksList: [], // 当前周日期列表
        /**情侣课表管理 */
        showcouples: false, // 情侣课表切换
        couples_openid: '',
        // editTableId: null,
        todayWeek: null,
        classTime: config.classTime,
        lovesTime: null,
        courseInfo: [], // 自己课表
        //默认课表
        viewCourse:null
    },
    /**返回首页 */
    backIndex(){
        wx.reLaunch({
          url: '/pages/index/index',
        })
    },
    /**切换情侣课表 */
    changeCouple() {
        var that = this;
        wx.showToast({
          title: '功能正在开发~',
          icon:'none'
        })
        // if (that.data.showcouples) {
        //     that.setData({
        //         showcouples: false
        //     }, () => {
        //         that.queryTable(that.data.showWeek);
        //     })
        // } else {
        //     wx.showLoading({
        //         title: '获取情侣信息',
        //         mask: true
        //     })
        //     wx.cloud.callFunction({
        //         name: 'edu-couples-api',
        //         data: {
        //             action: 'findCouple'
        //         },
        //         success: res => {
        //             if (res.result.errCode == -1) {
        //                 that.setData({
        //                     errMsg: res.result.errMsg
        //                 })
        //                 if(res.result.errMsg == '没有情侣信息'){
        //                     wx.showModal({
        //                       title:'提醒',
        //                       content:'是否前去绑定?',
        //                       success:r=>{
        //                           if(r.confirm){
        //                               wx.navigateTo({
        //                                 url: '/pages/edu/timetable/couples',
        //                               })
        //                           }
        //                       }
        //                     })
        //                 }
        //             } else {
        //                 // console.log(res)
        //                 that.setData({
        //                     showcouples: true,
        //                     couples_openid: res.result.otherBase.openid
        //                 }, () => {
        //                     that.queryTable(that.data.showWeek);
        //                 })
        //             }

        //         },
        //         complete: res => {
        //             wx.hideLoading();
        //             // console.log(res)
        //         }
        //     })
        // }

    },
    /**点击跳转登录 */
    tapLogin() {
        wx.getUserProfile({
            desc: '获取头像和昵称',
            success: res => {
                let userInfo = res.userInfo
                wx.showLoading({
                    title: '登录',
                    mask: true
                })
                wx.cloud.callFunction({
                    name: 'cloud-user-api',
                    data: {
                        action: 'userBind',
                        userInfo: userInfo
                    },
                    complete: res => {
                        console.log(res)
                        this.initTable();
                        wx.hideLoading();
                    }
                })
            }
        })
    },
    /**
     * 生成当前周的日期列表
     */
    weeksList(day) {
        // console.log(day.format("d"))
        let todayWeek = day.format("d") > 0 ? dayjs().format("d") - 1 : 6;
        let Fist = day.subtract(todayWeek, "day");
        console.log(todayWeek)
        let _week = [];
        for (let index = 0; index < 7; index++) {
            _week.push(Fist.add(index, "day").format("MM/DD"));
        }
        console.log(_week)
        this.setData({
            weeksList: _week,
            todayWeek
        });
    },

    onShow: function () {

    },
    hideModal(){
        this.setData({
            modalName:''
        })
    },
    /**预览课表 */
    viewCourse(e){
        console.log(e)
        let courseData = e.detail;
        this.setData({
            modalName:'courseModal',
            viewCourse:courseData
        })
    },
    /**初始化课表 */
    initTable() {
        var that = this;
        wx.showLoading({
            title: '初始化本周课表',
        })
        wx.cloud.callFunction({
            name: 'edu-timetable-api',
            data: {
                action: 'initTable'
            },
            success: res => {
                if (res.result.errCode == -1) {
                    setTimeout(function () {
                        wx.showModal({
                            title: '提示',
                            content: '是否跳转到登录页面',
                            success: r => {
                                if (r.confirm) {
                                    that.tapLogin();
                                }
                            }
                        })
                    }, 1000)
                    that.setData({
                        errMsg: res.result.errMsg
                    })
                } else {
                    /**请求并返回结果 */
                    that.setData({
                        courseInfo: res.result.timetableData,
                        currentWeek: res.result.currentWeek,
                        showWeek: res.result.currentWeek,
                        userInfo: res.result.userInfo
                    })
                }
                // console.log(res)

            },
            complete: res => {
                console.log(res)
                wx.hideLoading();
            }
        })
    },
    /**全局设置为custom -- 不需要再重复计算 */
    // InitCustom() {
    //     app.InitCustom();
    //     this.setData({
    //         StatusBar: app.globalData.StatusBar,
    //         CustomBar: app.globalData.CustomBar,
    //         displayArea: app.globalData.displayArea,
    //     })
    // },
    onLoad: function () {
        // this.InitCustom();
        console.log(app.globalData)
        // this.courseNum();
        this.initTable();
        this.weeksList(dayjs());
        let semester = null; // 当前是第几学S期
        let nowM = dayjs().format("M"); // 获取现在的月份
        semester = nowM < 3 || nowM > 9 ? 2 : 1;
        this.setData({
            semester,
            nowM
        });
        app.emitter.on('bindSucc', r => {
            this.initTable();
        })
        // let currentWeek = wx.getStorageSync("currentWeek");
        // if (app.globalData.userInfo) {
        //     this.setcourse(currentWeek);
        // }
    },
    onShareAppMessage: function (res) {
        if (res.from === "button") {
            // 来自页面内转发按钮
            console.log(res.target);
        }
        return {
            title: config.shareText,
            imageUrl: "/images/shareImg.png"
        };
    },
    // onShareTimeline: function (res) {
    //     if (res.from === "button") {
    //         // 来自页面内转发按钮
    //         console.log(res.target);
    //     }
    //     return {
    //         title: config.shareText,
    //         imageUrl: "/images/shareImg.png"
    //     };
    // },
    /**
     * 请求获取对应周次课表
     */
    queryTable(zc) {
        var that = this;
        wx.showLoading({
            title: '获取第' + zc + '周课表',
            mask: true
        })
        let params = {
            action: 'queryTable',
            zc
        }
        if (that.data.showcouples) {
            params.openid = that.data.couples_openid
        }
        wx.cloud.callFunction({
            name: 'edu-timetable-api',
            data: params,
            success: res => {
                that.setData({
                    courseInfo: res.result.timetableData,
                })
            },
            complete: res => {
                console.log(res)
                wx.hideLoading();
            }
        })
    },
    /**
     * 回到当前周
     */
    backToCurrent() {
        this.setData({
            showWeek: this.data.currentWeek,
            weeksSwitch: false,
        }, () => {
            this.queryTable(this.data.currentWeek)
        });
        this.weeksList(dayjs());
        // let currentWeek = wx.getStorageSync("currentWeek");
        // this.setcourse(currentWeek);
    },
    /**
     * 选择周
     */
    ChooseCheckbox(e) {
        console.log(e)
        let value = e.detail;
        let diff = value - this.data.currentWeek;
        this.setData({
            showWeek: value,
        }, () => {
            /**请求并获取当前周次课表 */
            this.queryTable(value)
        });
        // this.setcourse(value);
        if (diff == 0) {
            // 没有周数切换
            return;
        } else if (diff > 0) {
            let _add = dayjs().add(diff, "week");
            this.weeksList(_add);
        } else {
            let _sub = dayjs().subtract(-diff, "week");
            this.weeksList(_sub);
        }
    },
    /**
     * 周数切换
     */
    weeksSwitch() {
        // if (this.data.showWeek > 20) {
        //     return;
        // }
        this.setData({
            weeksSwitch: true,
        });
    },

    /**
     * 新增课表
     */
    addTable(e) {
        let id = e.detail;
        console.log(id)
        let day = parseInt(id % 7);
        let nums = parseInt(id / 7);
        wx.navigateTo({
            url: "edit?day=" + day + '&nums=' + nums
        });
    },
    /**
     * 新增课表
     */
    // importTable() {
    //     wx.navigateTo({
    //         url: "/pages/importTable/importTable",
    //     });
    // },
    /**
     * 编辑课表
     */
    editTable(e) {
        wx.navigateTo({
            url: "/pages/editingCourse/editingCourse?" +
                serializePathQuery({
                    id: e.detail,
                }),
        });
    },
    onShareAppMessage(){
        // let userInfo = wx.getStorageSync('userInfo')
        // // console.log(userInfo)
        // let realName = userInfo.realName;
        var that = this;
        let userInfo = that.data.userInfo
        return {
            title: `${userInfo.nickName}分享的课表`,
            path: 'pages/index/index?copyId='+userInfo.openid
        }
    }
});